package com.webframe.web.controller;

import java.text.ParseException;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

import org.directwebremoting.ScriptSession;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.proxy.ScriptProxy;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.webframe.po.Message;

/**
 * 聊天室消息类
 * @author lenovo
 *
 */
@Controller
@RequestMapping("/message")
public class MessageController extends BaseController {
	public static Map<String, TreeNode> onlineUsers = new TreeMap<String, TreeNode>();

	public static Map<Long, Message> messages = new TreeMap<Long, Message>();

	/**
	 * 发送消息
	 * 
	 */
	public String addMessage(String text, String sender) throws Exception {
		if (text != null) {
			Message msg = new Message();
			msg.setDate(new Date());
			msg.setSender(sender);
			msg.setText(text);
			WebContext wctx = WebContextFactory.get();
			String currentPage = wctx.getCurrentPage();
			Collection<ScriptSession> sessions = wctx.getScriptSessionsByPage(currentPage);
			ScriptProxy s = new ScriptProxy(sessions);
			s.addFunctionCall("receiveMessages", msg);
		}
		return "none";
	}

	/**
	 * 查询聊天历史记录
	 * @return
	 * @throws ParseException
	 */
	public String findChatHistory() throws ParseException {
		
		return null;
	}

	@SuppressWarnings("rawtypes")
	public String getOnlineUsers() {
		String jsonString = "";
		jsonString = "[";
		for (Iterator it = onlineUsers.entrySet().iterator(); it.hasNext();) {
			Map.Entry en = (Map.Entry) it.next();
			TreeNode tn = (TreeNode) en.getValue();
			jsonString += "{id:'" + tn.getId() + "'";
			jsonString += ",leaf:true,iconCls:'icon-user',";
			jsonString += "text:'" + tn.getText() + "'}";
			if (it.hasNext()) {
				jsonString += ",";
			}
		}
		jsonString += "]";
		return null;
	}

	public static class TreeNode {
		public String id;

		public String text;

		public String getId() {
			return this.id;
		}

		public void setId(String id) {
			this.id = id;
		}

		public String getText() {
			return this.text;
		}

		public void setText(String text) {
			this.text = text;
		}
	}
}